<?php
namespace app\controller;

use app\service\ArticleService;
use app\service\CategoryService;
use app\BaseController;
use app\service\GoodsService;
use think\App;
use think\exception\HttpException;
use think\facade\View;

class Category extends BaseController
{
    private $categoryService;
    private $articleService;
    private $goodsService;

    /**
     * Category constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->categoryService = app()->make(CategoryService::class);
        $this->articleService = app()->make(ArticleService::class);
        $this->goodsService = app()->make(GoodsService::class);
    }

    /**
     * @param $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($id): string
    {
        $data['detail'] = $this->categoryService->queryDetail($id);
        if (empty($data['detail'])) {
            return View::fetch('/error/index', array('msg'=>'抱歉，分类不存在'));
        }
        $data['parent'] = $this->categoryService->queryDetail($data['detail']['parent_id']);
        $categoryWhere['parent_id'] = $id;
        $childCategories = $this->categoryService->queryListByWhere($categoryWhere);
        $cidArr = array();
        if (!empty($childCategories)) {
            $cidArr = array_column($childCategories->toArray(), 'cid');
            foreach ($childCategories as $key=>$item) {
                $cidArr[] = $item['id'];
            }
        }
        $cidArr[] = $id;
        $where['cid'] = $cidArr;
        $page = $this->goodsService->queryListByPage($where, 'commission_rate desc',20);
        $data['pageInfo'] = $page['page'];
        $data['list'] = $page['data'];
        $data['page'] = $this->request->get('page');
        $data['brandList'] = $this->goodsService->queryListByNum('brand_id > 0', 'commission_rate desc',5);
        $data['settingKeywords'] = $data['detail']['keywords'];
        $data['settingDescription'] = $data['detail']['description'];
        $data['cid'] = $id;
        return View::fetch('index', $data);
    }
    public function detail(): string
    {
        return View::fetch('detail');
    }
}
